package com.donn.securitycontrolplatform.dangerousgood.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.donn.securitycontrolplatform.common.Result;
import com.donn.securitycontrolplatform.dangerousgood.entity.TStorage;
import com.donn.securitycontrolplatform.dangerousgood.response.Storage;
import com.donn.securitycontrolplatform.dangerousgood.response.StorageResponse;
import com.donn.securitycontrolplatform.dangerousgood.service.ITStorageService;
import com.donn.securitycontrolplatform.db1.mapper.TStorageMapper;
import com.donn.securitycontrolplatform.utils.DateUtil;
import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 库存服务实现类
 * </p>
 *
 * @author zhenglx
 * @since 2022-06-19
 */
@Service
@Slf4j
public class TStorageServiceImpl extends ServiceImpl<TStorageMapper, TStorage> implements ITStorageService {

    @Autowired
    TStorageMapper mapper;

    /**
     * 库存新增
     *
     * @param storage 库存实体
     * @return 结果
     */
    @Override
    public Result insertStorage(TStorage storage) {
        try {
            storage.setTime(LocalDateTime.now());
            storage.setUpdateTime(LocalDateTime.now());
            return Result.success(saveOrUpdate(storage));
        } catch (Exception e) {
            log.error("An error occurred in the insertStorage : ", e);
            return Result.init(500, "Service error", e.getMessage());
        }
    }

    /**
     * 修改库存
     *
     * @param storage 库存实体
     * @return 结果
     */
    @Override
    public Result updateStorage(TStorage storage) {
        try {
            storage.setUpdateTime(LocalDateTime.now());
            return Result.success(saveOrUpdate(storage));
        } catch (Exception e) {
            log.error("An error occurred in the updateStorage : ", e);
            return Result.init(500, "Service error", e.getMessage());
        }
    }

    /**
     * 库存删除
     *
     * @param storageId 库存id
     * @return 结果
     */
    @Override
    public Result deleteStorage(String storageId) {
        try {
            return Result.success(removeById(storageId));
        } catch (Exception e) {
            log.error("An error occurred in the deleteStorage : ", e);
            return Result.init(500, "Service error", e.getMessage());
        }
    }

    /**
     * 库存列表
     *
     * @param page 分页
     * @return
     */
//    @Override
//    public Result selectStorageList(Page page) {
//        try {
//            QueryWrapper<TStorage> queryWrapper = new QueryWrapper<>();
//            queryWrapper.lambda().eq(TStorage::getCategory, "高压气瓶");
//            return Result.success(page(page, queryWrapper));
//        } catch (Exception e) {
//            log.error("selectStorageList error :", e);
//        }
//        return Result.init(500, "fail", "");
//    }

    /**
     * 查询库存轻轻
     *
     * @param storageId 库存id
     * @return 库存详情
     */
    @Override
    public Result getStorageById(String storageId) {
        try {
            return Result.success(getById(storageId));
        } catch (Exception e) {
            log.error("An error occurred in the getStorageById : ", e);
            return Result.init(500, "Service error", e.getMessage());
        }
    }


    @Override
    public Result selectExplosiveList(String name, LocalDateTime startTime, LocalDateTime endTime, Page page) {
        QueryWrapper<TStorage> queryWrapper = new QueryWrapper<>();
        if (endTime != null && startTime != null) {
            queryWrapper.lambda().between(TStorage::getUpdateTime, startTime, endTime);
        }
        if (StringUtil.isNotEmpty(name)) {
            queryWrapper.lambda().eq(TStorage::getOperator, name);
        }
        return Result.success(page(page, queryWrapper));
    }

    @Override
    public Result getCurrentMonthExplosiveStorageInfo() {
        Map<String, Object> resultMap = mapper.getCurrentMonthStorages(DateUtil.monthOfFirstDate(LocalDate.now()), LocalDate.now());
        String inOperator = mapper.getCurrentMonthStorageInOperator(DateUtil.monthOfFirstDate(LocalDate.now()), LocalDate.now());
        String outOperator = mapper.getCurrentMonthStorageOutOperator(DateUtil.monthOfFirstDate(LocalDate.now()), LocalDate.now());
        resultMap.put("inOperator", inOperator);
        resultMap.put("outOperator", outOperator);
        return Result.success(resultMap);
    }

    @Override
    public Result getLastWeekStorageInfo() {
        List<StorageResponse> responses = mapper.getLastWeekStorage(LocalDateTime.now().plusDays(-6), LocalDateTime.now());
        Map<Integer, Integer> lastWeekMap = new HashedMap();
        lastWeekMap.put(DayOfWeek.MONDAY.getValue(), 0);
        lastWeekMap.put(DayOfWeek.TUESDAY.getValue(), 0);
        lastWeekMap.put(DayOfWeek.WEDNESDAY.getValue(), 0);
        lastWeekMap.put(DayOfWeek.THURSDAY.getValue(), 0);
        lastWeekMap.put(DayOfWeek.FRIDAY.getValue(), 0);
        lastWeekMap.put(DayOfWeek.SATURDAY.getValue(), 0);
        lastWeekMap.put(DayOfWeek.SUNDAY.getValue(), 0);
        List<Integer> dateList = responses.stream().map(StorageResponse::getDate).collect(Collectors.toList());
        for (Map.Entry<Integer, Integer> map : lastWeekMap.entrySet()) {
            if (!dateList.contains(map.getKey())) {
                responses.add(new StorageResponse(map.getKey(), 0, 0, 0));
            }
        }
        responses.sort(Comparator.comparing(StorageResponse::getDate));
        List<Integer> storageInQuantityList = responses.stream().map(StorageResponse::getStorageInQuantity).collect(Collectors.toList());
        List<Integer> storageOutQuantityList = responses.stream().map(StorageResponse::getStorageOutQuantity).collect(Collectors.toList());
        List<Integer> storageQuantityList = responses.stream().map(StorageResponse::getQuantity).collect(Collectors.toList());
        Storage storage = new Storage();
        storage.setStorageInQuantity(storageInQuantityList);
        storage.setStorageOutQuantity(storageOutQuantityList);
        storage.setStorageQuantity(storageQuantityList);
        return Result.success(storage);
    }
}
